# rclone安装脚本
# 用于在Windows系统上安装rclone

Write-Host "开始安装rclone..."

# 检查是否以管理员权限运行
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $isAdmin) {
    Write-Host "请以管理员权限运行此脚本"
    exit 1
}

try {
    # 获取系统架构
    $arch = $env:PROCESSOR_ARCHITECTURE
    Write-Host "系统架构: $arch"

    # 确定下载URL
    $downloadUrl = ""
    if ($arch -eq "AMD64") {
        $downloadUrl = "https://downloads.rclone.org/rclone-current-windows-amd64.zip"
    } elseif ($arch -eq "x86") {
        $downloadUrl = "https://downloads.rclone.org/rclone-current-windows-386.zip"
    } else {
        Write-Host "不支持的系统架构: $arch"
        exit 1
    }

    # 下载rclone
    Write-Host "下载rclone..."
    $zipFile = "$env:TEMP\rclone.zip"
    Invoke-WebRequest -Uri $downloadUrl -OutFile $zipFile

    # 解压文件
    Write-Host "解压文件..."
    $extractPath = "$env:TEMP\rclone_extract"
    Expand-Archive -Path $zipFile -DestinationPath $extractPath -Force

    # 获取解压后的目录名
    $rcloneDir = Get-ChildItem -Path $extractPath -Directory | Select-Object -First 1

    # 复制二进制文件到系统路径
    Write-Host "安装rclone..."
    $installPath = "C:\Program Files\rclone"
    if (!(Test-Path $installPath)) {
        New-Item -ItemType Directory -Path $installPath -Force
    }

    Copy-Item -Path "$($rcloneDir.FullName)\rclone.exe" -Destination $installPath -Force

    # 添加到系统PATH
    $envPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine)
    if ($envPath -notlike "*$installPath*") {
        [Environment]::SetEnvironmentVariable("Path", "$envPath;$installPath", [EnvironmentVariableTarget]::Machine)
        Write-Host "已将rclone添加到系统PATH"
    }

    # 清理临时文件
    Write-Host "清理临时文件..."
    Remove-Item -Path $zipFile -Force
    Remove-Item -Path $extractPath -Recurse -Force

    # 验证安装
    Write-Host "验证安装..."
    $rcloneVersion = & rclone --version
    Write-Host $rcloneVersion

    Write-Host "rclone安装完成!"
} catch {
    Write-Host "安装过程中出现错误: $($_.Exception.Message)"
    exit 1
}